package com.twu.biblioteca.main;

import com.twu.biblioteca.entity.Book;
import com.twu.biblioteca.entity.Movie;
import com.twu.biblioteca.entity.User;
import com.twu.biblioteca.util.Formatter;

import java.util.ArrayList;


public class Librarian {


    public Librarian(Library library)
    {
        this.library = library;
    }

    public String listBooks()
    {
        ArrayList<Book> availableBooks = library.getAllBooks();
        return Formatter.formatBooks(availableBooks);
    }

    public String listMovies()
    {
        ArrayList<Movie> availableMovies = library.getAllMovies();
        return Formatter.formatMovies(availableMovies);
    }

    public boolean authenticate(String userName,String password)
    {
         ArrayList<User> availableUsers = library.getAllUsers();
         for(User user: availableUsers)
         {
             if(user.getUserName().equals(userName) && user.getPassword().equals(password))
             {
                loggedInUser = user;
                return true;
             }
         }

        return false;
    }

    public void logout()
    {
        loggedInUser = null;
    }

    public String reserveBook(String searchText)
    {
        boolean foundISBN, foundBookName;
        String successMessage = "Thank You! Enjoy the book";
        String failureMessage = "Sorry we don't have that book yet.";
        foundBookName = isBookNameFound(searchText);

        if(foundBookName)
        {
            return successMessage;
        }

        foundISBN = isISBNFound(searchText);
        if(foundISBN)
        {
            return successMessage;
        }

        return failureMessage;
    }

    public String viewMembership()
    {
        if(loggedInUser != null)
        {
            return loggedInUser.toString();
        }

        return "Please talk to a Librarian. Thank you.";
    }
    public boolean isUserLoggedIn()
    {
        return loggedInUser != null;
    }

    public User getLoggedInUser()
    {
        return loggedInUser;
    }

    private boolean isISBNFound(String ISBN)
    {
        ArrayList<Book> books = library.getAllBooks();
        for(Book book: books)
        {
            if(book.getISBN().equals(ISBN) && book.isReserved() == false)
            {
                book.reserve();
                return true;
            }
        }
        return false;
    }

    private boolean isBookNameFound(String bookName)
    {
        ArrayList<Book> books = library.getAllBooks();
        for(Book book: books)
        {
            if(book.getName().equalsIgnoreCase(bookName) && book.isReserved() == false)
            {
                book.reserve();
                return true;
            }
        }
        return false;
    }

    private User loggedInUser;
    private Library library;
}
